package com.dcy.log.biz.service;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.dcy.common.enums.LogEnum;
import com.dcy.es.dto.PageResultOutputDTO;
import com.dcy.es.service.BaseElasticService;
import com.dcy.log.biz.dto.input.SearchInputDTO;
import com.dcy.log.biz.dto.output.ConsoleLog;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2020/10/9 15:17
 */
@Service
public class LogService {

    private static final String LOG_INDEX = "dcy-fast-cloud-request-log";
    @Autowired
    private BaseElasticService<ConsoleLog> baseElasticService;


    public PageResultOutputDTO<ConsoleLog> getBusinessLogPageList(SearchInputDTO searchInputDTO) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.trackTotalHits(true);
        // 分页查询
        searchSourceBuilder.from(PageUtil.getStart(searchInputDTO.getCurrent() - 1, searchInputDTO.getSize()));
        searchSourceBuilder.size(searchInputDTO.getSize());
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("doc.logEnum.keyword",LogEnum.BUSINESS.name()));
        if (StrUtil.isNotBlank(searchInputDTO.getSearch())) {
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(searchInputDTO.getSearch()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("@timestamp", SortOrder.DESC);
        return baseElasticService.page(LOG_INDEX, searchSourceBuilder, ConsoleLog.class);
    }

    public PageResultOutputDTO<ConsoleLog> getLoginLogPageList(SearchInputDTO searchInputDTO) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.trackTotalHits(true);
        // 分页查询
        searchSourceBuilder.from(PageUtil.getStart(searchInputDTO.getCurrent() - 1, searchInputDTO.getSize()));
        searchSourceBuilder.size(searchInputDTO.getSize());
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.should(QueryBuilders.matchQuery("doc.logEnum.keyword",LogEnum.LOGIN.name())).should(QueryBuilders.matchQuery("doc.logEnum.keyword",LogEnum.LOGOUT.name()));
        if (StrUtil.isNotBlank(searchInputDTO.getSearch())) {
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(searchInputDTO.getSearch()));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("@timestamp", SortOrder.DESC);
        return baseElasticService.page(LOG_INDEX, searchSourceBuilder, ConsoleLog.class);
    }

}
